package io.renren.modules.oss.cloud;

import java.io.*;

/**
 * 本地存储
 */
public class LocalStorageService extends CloudStorageService {


    public LocalStorageService(CloudStorageConfig config) {
        this.config = config;
    }

    @Override
    public String upload(byte[] data, String path) {
        OutputStream os = null;
        try {
            File f = new File(path);
            if (!f.getParentFile().exists()) {
                File parentDir = new File(path.substring(0, path.lastIndexOf("/")));
                parentDir.mkdirs();
            }
            os = new FileOutputStream(path);
            os.write(data, 0, data.length);
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            File f = new File(path);
            if (f.exists()) {
                f.delete();
            }
        } finally {
            try {
                os.close();
            } catch (IOException ioe) {
            }
        }
        return path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        String path = upload(data, getPath(config.getLocalURI(), suffix));
        return path.replace(config.getLocalURI(),config.getLocalURL());
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        OutputStream os = null;
        try {
            File f = new File(path);
            if (!f.exists()) f.mkdirs();
            os = new FileOutputStream(path);
            byte buffer[] = new byte[1024];
            int count;
            while ((count = inputStream.read(buffer)) > 0) {
                os.write(buffer, 0, count);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            File f = new File(path);
            if (f.exists()) {
                f.delete();
            }
        } finally {
            try {
                os.close();
            } catch (IOException ioe) {


            }
        }
        return path;
    }


    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getLocalURI(), suffix));
    }
}
